package com.hcb.tonguetiphealth.widget.more;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.LocationClient;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.Location;
import com.hcb.tonguetiphealth.manager.ReadCityFromXml;
import com.hcb.tonguetiphealth.util.HypyUtil;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.Sorter;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;
import com.hcb.tonguetiphealth.widget.recommendhealth.RecommendHealthWidget;
import com.hcb.tonguetiphealth.widget.resbook.RestaurantBookWidget;

public class ChangeCityWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "ChangeCityWidget";

	private Activity ctx;
	private Handler mHandler;
	private LinearLayout linearLayoutBack, llCitys;
	private Location location;
	private LocationClient mLocClient;
	private String city;
	private TextView tvCity;
	private Button btCitySearch;
	private EditText etCitySearch;
	
	private String lat;
	private String lng;
	
	private Map<String, String>cityMap;//存储城市名、城市id
	private Map<String, List<String>>initialCityMap;//存储首字母对应的城市列表
	private String fromWidget;
	private String currentCityId;
	private final static String BaiduMapKey = "DF45D1401C31C5328897DE20D783E03930CCA49B";

	// 百度经纬度解析成地址
	// http://api.map.baidu.com/geocoder?output=json&location=39.983424,%20116.322987&key=37492c0ee6f924cb5e934fa08c6b1676
	// 返回格式：
	// {
	// "status":"OK",
	// "result":{
	// "location":{
	// "lng":117.308382,
	// "lat":31.804274
	// },
	// "formatted_address":"安徽省合肥市包河区g40",
	// "business":"骆岗",
	// "addressComponent":{
	// "city":"合肥市",
	// "district":"包河区",
	// "province":"安徽省",
	// "street":"g40",
	// "street_number":""
	// },
	// "cityCode":127
	// }
	// }
	private static String baiduGeocoderUrl = "http://api.map.baidu.com/geocoder?output=json";

	public ChangeCityWidget(Context context) {
		super(context);
		ctx = (Activity) context;
		inflate(context, R.layout.location_city, this);
		fromWidget = ctx.getIntent().getStringExtra("fromWidget");
		SharedPreferences preferences = ctx.getSharedPreferences(Global.CITYID, 0);
		currentCityId = preferences.getString(Global.CITYID, Global.defaultCityId);
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在确定您的位置...");
					break;
				case MessageWhat.BAIDU_LAOCATION_SUCESS:
					mLocClient.stop();
					Global.lat = String.valueOf( location.getLatitude() );
					Global.lng = String.valueOf( location.getLongitude() );
					lat = Global.lat;
					lng = Global.lng;
					initData();
					break;
				case MessageWhat.BAIDU_LOCATINO_CITY_SUCESS:
					dismissMessageDialog();
					tvCity.setText(city);
					break;
				default:
					break;
				}
			}
		};
		bindView();
		bindEvent();
		if (Global.lat !=null && Global.lng!=null) {
			mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
			initData();
		}else {
			//百度定位sdk
			location = new Location(ctx.getApplicationContext(), mHandler);
			mLocClient = location.mLocationClient;
			mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
			mLocClient.start();
		}
		
		setCitys(null);
		addCityViews();
	}

	/**
	 * 动态添加城市列表
	 */
	private void addCityViews(){
		
		llCitys.removeAllViews();
		Set<Map.Entry<String, List<String>>> set = initialCityMap.entrySet();
		for (Iterator<Map.Entry<String, List<String>>> it = set.iterator(); it.hasNext();) {
			Map.Entry<String, List<String>>entry =( Map.Entry<String, List<String>> )it.next();
			String inital = entry.getKey();
			List<String>cityList = entry.getValue();
			
			LinearLayout llCityHorizion = new LinearLayout(ctx);
			llCityHorizion.setOrientation(LinearLayout.HORIZONTAL);
			llCitys.addView(llCityHorizion);
			
			TextView tvInital = new TextView(ctx);
//			textView.setId(id)
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);  
			lp.setMargins(5, 5, 5, 5);  
			tvInital.setLayoutParams(lp); 
			tvInital.setText(inital);
			tvInital.setTextColor(0xfff8510d);//0xffff00ff是int类型的数据，分组一下0x|ff|ff00ff，0x是代表颜色整数的标记，ff是表示透明度，ff00ff表示颜色，注意：这里ffff00ff必须是8个的颜色表示，不接受ff00ff这种6个的颜色表示。
			tvInital.setTextSize(16);
			llCityHorizion.addView(tvInital);
			
			for (int i = 0; i < cityList.size(); i++) {
				final TextView tvCity = new TextView(ctx);
				
				tvCity.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						System.out.println("cityname:"+tvCity.getText().toString());
						String city = tvCity.getText().toString();
						String cityId = cityMap.get(city);
						//存储定位的城市
						SharedPreferences preferences = ctx.getSharedPreferences(Global.CITYID, 0);
						SharedPreferences.Editor editor = preferences.edit();
						editor.putString(Global.CITYID, cityId);
						editor.commit();
						if ("RestaurantBookWidget".equals(fromWidget)) {
							ctx.setContentView(new RestaurantBookWidget(ctx));
						}else if("RecommendHealthWidget".equals(fromWidget)) {
							ctx.setContentView(new RecommendHealthWidget(ctx));
						}
						
					}
				});
				tvCity.setOnTouchListener(new OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (event.getAction() == KeyEvent.ACTION_DOWN) {
							tvCity.setTextColor(0xfff8510d);
						}else {
							tvCity.setTextColor(0xff5c5c5c);
						}
						return false;
					}
				});
//				lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);  
//				lp.setMargins(2, 2, 2, 2);  
				String city = cityList.get(i);
				tvCity.setLayoutParams(lp); 
				tvCity.setText(city);
				if (currentCityId.equals(cityMap.get(city))) {
					tvCity.setTextColor(0xfff8510d);
				}else {
					tvCity.setTextColor(0xff5c5c5c);
				}
				tvCity.setTextSize(16);
				llCityHorizion.addView(tvCity);
			}
		}
	}
	
	
	/**
	 *从xml读取城市，并按城市首字母分类 
	 */
	private void setCitys(String keyCity){
		
		initialCityMap = new HashMap<String, List<String>>();
		
		ReadCityFromXml readCityFromXml = new ReadCityFromXml(ctx);
		cityMap = readCityFromXml.getCitys();
		
		Set<Map.Entry<String, String>> set = cityMap.entrySet();
		for(Iterator<Map.Entry<String, String>> iterator = set.iterator();iterator.hasNext();){
			Map.Entry<String, String>entry =( Map.Entry<String, String> )iterator.next();
			String city = entry.getKey();
			//过滤搜索的关键字
			if (keyCity !=null && !city.contains(keyCity)) {
				continue;
			}
			//获取首字母，并将该城市放入首字母的城市列表中;该算法不支持多音字
			String initial = HypyUtil.getInitial(city);
			if (initial.length() > 0) {
				initial = initial.substring(0,1).toUpperCase();
			}
			if (city.equals("重庆市")) {
				initial = "C";
			}
			if (initialCityMap.get(initial) == null) {
				initialCityMap.put(initial, new ArrayList<String>());
			}
			List<String> cityList = initialCityMap.get(initial);
			cityList.add(city);
		}
		// 根据首字母排序
		initialCityMap = Sorter.sort(initialCityMap);
	}
	
	private void initData() {

		if (location!=null && location.getCity() != null) {
			city = location.getCity();
			mHandler.sendEmptyMessage(MessageWhat.BAIDU_LOCATINO_CITY_SUCESS);
		} else {
			// 通过gps定位则再获取一次城市
			new Thread() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					//像百度api发起请求
					baiduGeocoderUrl += "&location=" + Global.lat + ","
							+ Global.lng + "&key=" + BaiduMapKey;
					HttpClient client = new DefaultHttpClient();
					HttpGet get = new HttpGet(baiduGeocoderUrl);
					HttpResponse response;
					String reply = null;
					try {
						for (int i = 0; i < 3; i++) {
							response = client.execute(get);
							if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
								reply = EntityUtils.toString(response
										.getEntity());
								System.out.println("repley:"+reply);
							}
							if (reply != null) {
								break;
							}
						}
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (reply != null) {
						try {
							JSONObject jsonObject = new JSONObject(reply);
							String status = jsonObject.getString("status");
							if ("OK".equals(status)) {
								JSONObject objResult = jsonObject
										.getJSONObject("result");
								JSONObject objAddress = objResult
										.getJSONObject("addressComponent");
								city = objAddress.getString("city");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					mHandler.sendEmptyMessage(MessageWhat.BAIDU_LOCATINO_CITY_SUCESS);
				}
			}.start();
		}

	}

	private void bindView() {
		linearLayoutBack = (LinearLayout) findViewById(R.id.city_change_back);
		tvCity = (TextView) findViewById(R.id.city_located_tv);
		llCitys = (LinearLayout)findViewById(R.id.citys_linearlayout); 
		btCitySearch = (Button)findViewById(R.id.city_search_button);
		etCitySearch = (EditText)findViewById(R.id.city_search_et);
	}

	private void bindEvent() {
		linearLayoutBack.setOnClickListener(this);
		tvCity.setOnClickListener(this);
		btCitySearch.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.city_change_back:
			if (mLocClient != null) {
				mLocClient.stop();
			}
			if ("RestaurantBookWidget".equals(fromWidget)) {
				ctx.setContentView(new RestaurantBookWidget(ctx));
			}else if("RecommendHealthWidget".equals(fromWidget)) {
				ctx.setContentView(new RecommendHealthWidget(ctx));
			}
			break;
		case R.id.city_located_tv:
			String city = tvCity.getText().toString();
			String cityId = cityMap.get(city);
			//存储定位的城市
			SharedPreferences preferences = ctx.getSharedPreferences(Global.CITYID, 0);
			SharedPreferences.Editor editor = preferences.edit();
			editor.putString(Global.CITYID, cityId);
			editor.commit();
			if ("RestaurantBookWidget".equals(fromWidget)) {
				ctx.setContentView(new RestaurantBookWidget(ctx));
			}else {
				ctx.setContentView(new RecommendHealthWidget(ctx));
			}
			break;
		case R.id.city_search_button:
			String etStrCity = etCitySearch.getText().toString().trim();
			if (etStrCity == null || etStrCity.equals("")) {
				showMessage(ctx, "搜索关键字不能为空");
				return;
			}
			setCitys(etStrCity);
			addCityViews();
			break;
		default:
			break;
		}
	}

	@Override
	public void notifyAdapter() {

	}
 
}


